package com.lintesis.lintesismodel.common.hibernate;

import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;

import org.hibernate.Session;
import com.lintesis.utils.reflection.ReflectionUtils;




@SuppressWarnings("unchecked")
@MappedSuperclass
public abstract class BussinessObject
{

	public abstract Integer getId();

	@ManyToOne
	@Transient
	private GenericDAO genericDao = null;
	@Transient
	private Session session2 = null;

	public BussinessObject()
	{
		if (genericDao == null && session2 != null)
			genericDao = new GenericDAO(this.obtainHibernateSession());

	}

	public BussinessObject(Session session)
	{
		this.session2 = session;
		if (genericDao == null && session2 != null)
			genericDao = new GenericDAO(this.obtainHibernateSession());

	}

	public void delete() throws Exception
	{
		doBeforeDelete();		
		obtainGenericDao().delete(this);
		doAfterDelete();
	}

	public void save()
	{
		doBeforeSave();
		obtainGenericDao().save(this); 
		doAfterSave();
	}

	public void update()
	{
		doBeforeSave();
		obtainGenericDao().update(this);
		doAfterSave();
	}
	public void saveOrUpdate()
	{
		doBeforeSave();
		obtainGenericDao().saveOrUpdate(this);
		doAfterSave();
	}
	
	public abstract void doBeforeSave();

	public abstract void doAfterSave();

	public abstract void doBeforeDelete() throws Exception;

	public abstract void doAfterDelete() throws Exception;

	@Override
	public boolean equals(Object object)
	{
		boolean retorno = false;
		try
		{//lo agregue, borrar si no anda
//			if(object instanceof BussinessObject){
//				object = (BussinessObject) object;
//				if(((BussinessObject) object).getId()!=null && ((BussinessObject) object).getId().equals(this.getId()))
//					retorno = true;
//		
//			}
//	
				retorno = ReflectionUtils.compareObjects(this, object, 1);

		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return retorno;
	}

	public Session obtainHibernateSession()
	{
		if (session2 == null)
		{
			session2 = ConnectionManager.getSession();
		}
		return session2;
	}

	public void putSession(Session session)
	{
		this.session2 = session;
	}

	 public GenericDAO obtainGenericDao() {
	 if(genericDao==null)
	 genericDao=new GenericDAO(this.obtainHibernateSession());
	 return genericDao;
	 }
	
	 public void putGenericDao(GenericDAO genericDao) {
	 this.genericDao = genericDao;
	 }
	public abstract String getObjectDescription();
}
